#include "main.h"

void init()
{
	int code = 0;
	char buf[50];
	memset((void *)buf, 0 ,sizeof(buf));
	printTitle();
	connectionToServer();
	code = sendCommandAndGetRsp(HELLO_STR, buf);
	//printf("%d\n", code);
	
	if(code!=SERVER_RSP)
	{
		perror("Say hello Error!\n");
		exit(1);
	}
}

void auth()
{
	int code = 0;
	char buf[50];
	int auth_success = 0;
	char c;

	memset((void *)buf, 0 ,sizeof(buf));
	
	do
	{
		code = sendCommandAndGetRsp(AUTH_STR, buf);		
		if(code!=SERVER_AUTH)
		{
			perror("Auth login command Error!\n");
			printf(" ******* Try Again ? ******* \n");
			printf(" ******* Press [Y/y] to try ****** \n");
			c = getchar();
			if(c=='y'||c=='Y')
				continue;
			else
				exit(0); 
		}
		
		const char* tmp = getUserName();
		if(tmp==NULL)
		{
			printf(" ******** Enter valid user name ! ******* \n");
			continue;
		}

		char formatBuf[strlen(tmp)+2];
		memset(formatBuf, 0, sizeof(formatBuf));
		sprintf(formatBuf,"%s\r\n", tmp);
		
		code = sendCommandAndGetRsp(formatBuf, buf);
		free((void *)tmp);
		
		if(code==SERVER_BUSY)
			continue;

		tmp = getPassword();
		if(tmp==NULL)
		{
			printf(" ******** Enter valid password ! ******* \n");
			continue;
		}

		memset(formatBuf, 0, sizeof(formatBuf));
		sprintf(formatBuf,"%s\r\n", tmp);
		
		code = sendCommandAndGetRsp(formatBuf, buf);
		free((void *)tmp);
		
		if(code==SERVER_AUTH_SUCCESS)
			auth_success = 1;	

		if(auth_success==0)
		{
			printf(" ******* Continue to Auth ? ******** \n");
			printf(" ******* Press [Y/y] to continue ****** \n");
			char c = getchar();
			if(c=='y'||c=='Y')
				continue;
			else
				exit(0);
		}
	}
	while(auth_success==0);	

}

void setSender()
{
	char buf[50];
	int code = sendCommandAndGetRsp(getSourceAddress(), buf);
	if(code!=SERVER_RSP)
	{
		printf("Set Sender failed...!\n");
		exit(1);
	}
		
}

void setAddress()
{
	char buf[50];
	char c;
	int flag = 0;
	
	while(flag==0)
	{
		memset((void *)buf, 0 ,sizeof(buf));
		int code2 = sendCommandAndGetRsp(getTargetAddress(), buf);
		
		if(code2==SERVER_RSP)
		{
			flag = 1;
		//	printf("flag:%d\n",flag);
		}
		else
		{
			printf(" ******* Set source address error , try agagin ? Press [Y/y] ******* \n");
			c = getchar();
			
			if(c=='y'||c=='Y')
				continue;
			else
				exit(1);				
		}		
	}	
}

void sendText()
{
	char buf[50];
	memset((void *)buf, 0 ,sizeof(buf));
	
	int code = sendCommandAndGetRsp(DATA_STR, buf);
	if(code!=SEVEER_DATA_START)
	{
		printf(" Set data Command error! **\n");
		exit(1);
	}
	code = sendCommandAndGetRsp(getData(), buf);
	if(code!=SERVER_RSP)
	{
		printf(" ** Send text error! ** \n");
		exit(1);
	}
		
}

int main(int argc, char* argv[])
{	
	init();
	auth();
	setSender();
	setAddress();
	sendText();
	printf(" ******** Xinzaibing's client will exit... ********\n");
	getchar();
}


